<?php

//
// +------------------------------------------------------------------------+
// | PHP Version 5.4                                                        |
// +------------------------------------------------------------------------+
// | Copyright (c) All rights reserved.                                     |
// +------------------------------------------------------------------------+
// | 世纪车来车往(北京）网络科技有限公司 版权所有！                         |
// | TEL:010-63732365  HOTLINE:400-6688-365  EMAIL:clcw@clcw.com.cn         |
// | $Revision: 1.0 $                                                       |
// +------------------------------------------------------------------------+
// | Author: songaimin@clcw.com.cn  Blog:http://blog.csdn.net/samxx8        |
// +------------------------------------------------------------------------+
//

namespace AuctionCore\CarDealer;

use AuctionAppApi\Service\ThriftBailService;
use AuctionCore\System\AuctionException;

/**
 * 资产中心功能类
 * @author  Eric Lee
 */
class AssetCenter {

    private $dealer_id = null;

    /**
     * 构造
     * @param    int $dealer_id 车商id
     * @return   void
     */
    public function __construct($dealer_id = '') {
        $this->dealer_id = $dealer_id;
    }

    /**
     * 保证金情况
     * 返回array(保证金总额，可用保证金，冻结保证金，累计赔付金额)
     * @return   Array
     */
    public function bail_situation() {
        return M('car_dealer')->where("dealer_id='" . $this->dealer_id . "'")
                        ->field('bail_amount, bail_amount AS available_amount ,freeze_amount, indemnity_amount ')->find();
    }

    /**
     * 保证金充值：记录充值日志，并计算可用额度和冻结额度并计算可用额度和冻结额度
     * 返回array(可用额度,冻结额度
     * @param $occur_money 发生金额
     * @param $recharge_method 充值方式1支付宝 2拉卡拉 3线下充值 4网银 5代金券
     * @param msg 备注信息
     * @return   Array
     */
    public function bail_rechange($occur_money, $recharge_method = 3, $msg = '保证金充值',$out_trade_no='',$order_id=0,$colle_state=0) {
        $dealer_id = $this->dealer_id;

        if (!is_numeric($dealer_id) || $dealer_id <= 0) {
            AuctionException::make_throw('500001');
        }
        if (!is_numeric($occur_money) || $occur_money <= 0) {
            AuctionException::make_throw('500004');
        }
        if((int)$occur_money != $occur_money){
            AuctionException::make_throw('500016');
        }

        $now = date("Y-m-d H:i:s", time());
        $dealer = new Dealer($dealer_id);
        $dealer_info = $dealer->dealer_base_info();

        //追加保证金记录
        $bail_log_info = array(
            'dealer_id' => $dealer_id //int(10)车商id
            //,'order_id'=>$order_id //int(10)拍单号
            , 'use_type' => 1 //smallint(3)保证金应用类型 充值
            , 'use_detail' => $msg //text应用明细
            , 'occur_money' => $occur_money //double(10,2)发生金额
            , 'recharge_method' => $recharge_method //充值方式
            , 'remain_amount' => ($dealer_info['bail_amount'] + $occur_money)  //余额
            , 'createtime' => $now //datetime创建时间
            , 'use_time' => $now
            , 'recharge_no'=>$out_trade_no
            , 'recharge_id'=>$order_id
            , 'collection_id'=>$colle_state
        );
        $bail_log = M('dealer_bail_log');
        $log_id = $bail_log->add($bail_log_info);

        //更新车商保证金总数
        $dealer = M('car_dealer');
        if (intval($log_id) > 0) {
            $ok = $dealer->where(" dealer_id={$dealer_id} ")->setInc('bail_amount', $occur_money);
        } else {
            //充值失败
            AuctionException::make_throw('500067');
        }

        //保证金信息
        $ret = $dealer->field('dealer_id,bail_amount,freeze_amount')->find($dealer_id);
        return $ret;
    }

    /**
     * 保证金提取：记录提取日志，并计算可用额度和冻结额度并计算可用额度和冻结额度
     * 返回array(可用额度,冻结额度
     * @param $extract_money 发生金额
     * @param $extract_method 充值方式1支付宝 2拉卡拉 3线下充值 4网银 5代金券
     * @param msg 备注信息
     * @return   Array
     */
    public function bail_extract($extract_money, $extract_method = 3, $msg = '保证金提取') {
        $dealer_id = $this->dealer_id;

        if (!is_numeric($dealer_id) || $dealer_id <= 0) {
            AuctionException::make_throw('500001');
        }
        if (!is_numeric($extract_money) || $extract_money <= 0) {
            AuctionException::make_throw('500004');
        }
        if((int)$extract_money != $extract_money){
            AuctionException::make_throw('500016');
        }
        $now = date("Y-m-d H:i:s", time());
        $dealer = new Dealer($dealer_id);
        $dealer_info = $dealer->dealer_base_info();
        if ($extract_money > $dealer_info['bail_amount']) {
            AuctionException::make_throw('500015');
        }
        //追加保证金记录
        $bail_log_info = array(
            'dealer_id' => $dealer_id //int(10)车商id
            , 'use_type' => 4 //smallint(3)保证金应用类型 提取
            , 'use_detail' => $msg //text应用明细
            , 'occur_money' => $extract_money //double(10,2)发生金额
            , 'recharge_method' => $extract_method //提取方式
            , 'remain_amount' => ($dealer_info['bail_amount']  - $extract_money)  //余额
            , 'createtime' => $now //datetime创建时间
            , 'use_time' => $now
        );
        $bail_log = M('dealer_bail_log');
        $log_id = $bail_log->add($bail_log_info);

        //更新车商保证金总数
        $dealer = M('car_dealer');
        if (intval($log_id) > 0) {
            $ok = $dealer->where(" dealer_id={$dealer_id} ")->setDec('bail_amount', $extract_money);
        } else {
            //提取失败
            AuctionException::make_throw('500067');
        }

        //保证金信息
        $ret = $dealer->field('dealer_id,bail_amount,freeze_amount')->find($dealer_id);
        return $ret;
    }

    /**
     * 保证金日志列表
     * 根据条件返回保证金使用列表，默认时间倒序
     * @param    String $condition 条件
     * @param    String $order_by 排序
     * @param    int $offset 列表偏移量
     * @param    int $limit 列表limit
     * @return   Array
     */
    public function get_bail_logs($page = 1, $limit = 5, $params) {
        $page = (int) $page < 1 ? 1 : $page;
        $limit = (int) $limit < 1 ? 5 : $limit;
        $map = array();
        $map['dealer_id'] = array('eq', $this->dealer_id);
        $map['occur_money'] = array('gt',0);
        //保证金使用类型
        if (!empty($params['use_type'])) {
            $map['use_type'] = array('eq', $params['use_type']);
        }
        //发生时间
        if (!empty($params['use_time'])) {
            $map['use_time'] = array('like', $params['use_time']);
        }
        //是否解冻    
        if (isset($params['is_free']) && $params['is_free'] > -1) {
            $map['is_free'] = array('eq', $params['is_free']);
        }
//        $total = M('dealer_bail_log')->where($map)->count();
//        $logs = M('dealer_bail_log')->where($map)->field('recharge_no,recharge_method,order_id,use_type,use_time,occur_money,remain_amount,use_detail')->order('bl_id desc')->limit($limit)->page($page)->select();
        $bail = new ThriftBailService();
        $result = $bail->getBailLogsByDealerId($this->dealer_id,$params['use_type'],$params['use_time'],$page,$limit,$params['is_free'],'');
        if($result->code=='000000'){
            $logs = json_decode($result->data['logs'],true);
        }else{
            return false;
        }
        foreach ($logs['logs'] as $k => $v) {
            $order_no = M('order')->where("order_id='" . $v['order_id'] . "'")->getField('order_no');

            switch($v['recharge_method']){
                case '1':
                    $third_party = '支付宝';break;
                case '2':
                    $third_party = '拉卡拉';break;
                case '3':
                    $third_party = '线下';break;
                case '4':
                    $third_party = '网银';break;
                case '5':
                    $third_party = '代金券';break;
            }
            switch ($v['use_type']) {
                case '1':
                    $msg = $third_party.'充值保证金';
                    if($v['recharge_method']==1 || $v['recharge_method']==2){
                        $msg = $third_party.'充值保证金，支付订单【'.$v['recharge_no'].'】';
                    }
                    break;
                case '2':$msg = '对拍单【' . $order_no . '】  进行出价， 冻结保证金。';
                    break;
                case '3':$msg = '解冻出价保证金，拍单【' . $order_no . '】';
                    break;
                // case '4':$msg = '提取，拍单【'.$order_no.'】';break;
                case '4':$msg = '提取';
                    break;
                case '5':$msg = '扣除。拍单【' . $order_no . '】';
                    break;
                case '6':$msg = '扣除。拍单【' . $order_no . '】';
                    break;
                case '7':$msg = '其它';
                    break;
                case '8':$msg = '车辆维保信息查询透支,金额扣除。';
                    break;
                default:;
            }
            $v['use_detail'] = $msg;
            $logs[$k] = $v;
        }
        $res = array(
            'logs' => $logs,
            'total' => $result->data['nums']
        );
        return $res;
    }

    /**
     * 查询日志总数
     * @param    String $condition 条件
     * @return   int 条数
     */
    public function get_bail_log_count($condition = false) {
        $condition = trim($condition);
        $dealer_id = $this->dealer_id;
//      if($dealer_id){
//         $condition = " dealer_id = '{$dealer_id}' ".($condition?' and '.$condition:'');         
//      }
        //$condition ='';
        $num = M('dealer_bail_log')->where($condition)->count();
        return $num;
    }

    /**
     * 代金券列表，，默认时间倒序
     * @param    int $cond 条件
     * @param    int $offset 偏移量
     * @param    int $limit 限制
     * @return   Array
     */
    public function get_coupons($cond, $order = 'dc.createtime desc', $offset = '0', $limit = '20') {
        $res = M('dealer_coupon')->alias('dc')
                        ->join(C('DB_PREFIX') . "coupon c on c.coupon_id=dc.coupon_id")
                        ->field("dc.*,c.emp_id as c_emp_id,c.title,c.type,c.status as c_status")
                        ->where("dc.dealer_id='" . $this->dealer_id . "'")->where($cond)->order($order)->limit($offset, $limit)->select();
        return $res;
    }

    /**
     * 冻结车商保证金
     * @param 车商id
     * @param int order_id 使用保证金的拍单id
     * @param $msg 保证金使用描述
     * @param $occur_money 冻结金额
     * @return true/false   成功、失败
     */
    public function freeze($order_id, $occur_money = 2000, $msg = '冻结保证金') {
        if (!is_numeric($order_id) || $order_id <= 0) {
            AuctionException::make_throw('500055');
        }
        $dealer_id = $this->dealer_id;
        $now = date("Y-m-d H:i:s", time());

        $bail_log = M('dealer_bail_log');
        /*
          $info = $bail_log->query("SELECT SUM(IF(use_type=2,occur_money,0)) AS freeze_amount,SUM(IF(use_type=3,occur_money,0)) AS free_amount FROM au_dealer_bail_log WHERE dealer_id='{$dealer_id}' and order_id='{$order_id}';");
          if($info && ($info[0]['freeze_amount']>$info[0]['free_amount'])){
          //是否已经冻结
          return true;
          } */
        //todo 开发机已经测试通过.................................
        $prefix = C('DB_PREFIX');
        $rows = M()->query("SELECT `occur_money` freze_money FROM `{$prefix}dealer_bail_log` WHERE `order_id`='{$order_id}' AND `dealer_id`='{$dealer_id}' AND `use_type`=2 AND is_free=0;");
        if ($rows && count($rows) > 0 && $rows[0]['freze_money'] > 0) {
            //是否已经冻结
            return true;
        }

        //生成冻结描述
        /* $row = M()->query("SELECT CONCAT('对拍品  【',pad.`city_name`,ad.`city_name`,'】 ',mb.`name` ,' ',s.`name` ,m.`name`,' 进行出价，冻结保证金。') msg
          FROM  au_order o
          LEFT JOIN au_cars car ON car.car_id = o.`car_id`
          LEFT JOIN au_addr_area ad ON car.reg_city=ad.city_code
          LEFT JOIN au_addr_area pad ON ad.pid=pad.city_code
          LEFT JOIN au_car_model m ON car.`model_id` = m.`model_id`
          LEFT JOIN `au_car_series` s ON m.`series_id` = s.`series_id`
          LEFT JOIN au_car_brand b ON s.`brand_id` = b.`brand_id`
          LEFT JOIN au_car_mbrand mb ON b.`mbrand_id` = mb.`mbrand_id`
          WHERE  o.`order_id` = {$order_id} ;"); */
        $row = M()->query("SELECT CONCAT('对拍单【',o.order_no,',',car.car_id,'】 ',' 进行出价， 冻结保证金。') msg
               FROM  au_order o
               INNER JOIN au_cars car ON car.car_id = o.`car_id`  
               WHERE  o.`order_id` = '" . $order_id . "'");
        if (count($row) > 0) {
            $msg = $row[0]['msg'];
        }

        //车商信息
        $dealer = new Dealer($dealer_id);
        $dealer_info = $dealer->dealer_base_info();
        if ($dealer_info['bail_amount'] < $occur_money) { //保证金不足
            AuctionException::make_throw('500051');
        }


        //保证金使用记录
        $remain_amount = ($dealer_info['bail_amount'] - $occur_money);
        $bail_log_info = array(
            'dealer_id' => $dealer_id //int(10)车商id
            , 'order_id' => $order_id //int(10)拍单号
            , 'use_time' => $now //datetime保证金使用时间
            , 'use_type' => 2 //smallint(3)保证金应用类型 冻结出价保证金
            , 'use_detail' => $msg //text应用明细
            , 'occur_money' => $occur_money //double(10,2)发生金额
            , 'remain_amount' => $remain_amount  //余额
            , 'createtime' => $now //datetime创建时间
        );
        $log_id = $bail_log->add($bail_log_info);

        //更新车商保证金
        $up_info = array();
        $up_info['freeze_amount'] = ($dealer_info['freeze_amount'] + $occur_money);
        $up_info['bail_amount'] = $remain_amount;
        $eff = M('car_dealer')->where(" dealer_id='{$dealer_id}' ")->save($up_info);
        if (!(intval($eff) > 0)) {
            AuctionException::make_throw('500052');
        }


        return true;
    }

    /**
     * 解东拍单所有冻结的保证金
     */
    public static function free_all($order_id) {
        $m = M();
        $sql = "call `paimai_refund`('{$order_id}' ,'0');";
        $r = $m->execute($sql);
        return true;
    }

    /**
     * 解冻拍单的其它车商的保证金
     * @param 车商id
     * @param int order_id 使用保证金的拍单id
     * @param $msg 保证金使用描述
     * @return true/false   成功、失败
     */
    public function free($order_id, $msg = '解冻保证金') {

        $dealer_id = $this->dealer_id;
        $m = M();
        $sql = "call `paimai_refund`('{$order_id}' ,'{$dealer_id}' );";
        $r = $m->execute($sql);
        return true;


        /* if( !is_numeric($order_id) || $order_id<=0 ){
          AuctionException::make_throw('500055');
          }
          $dealer_id = $this->dealer_id;
          $now = date("Y-m-d H:i:s",time());

          $bail_log = M('dealer_bail_log');
          $info = $bail_log->query("SELECT SUM(IF(use_type=2,occur_money,0)) AS freeze_amount,SUM(IF(use_type=3,occur_money,0)) AS free_amount FROM au_dealer_bail_log WHERE dealer_id='{$dealer_id}' and order_id='{$order_id}';");
          if($info && ($info[0]['freeze_amount']==$info[0]['free_amount'])){
          //是否已经解冻
          return true;
          }

          $info = $bail_log->field('bl_id,occur_money,use_time')->where("dealer_id='{$dealer_id}' and order_id='{$order_id}' and use_type=2")->find();
          $occur_money = $info['occur_money'];
          $use_time = $info['use_time'];
          if(!$occur_money){
          AuctionException::make_throw('500051'); //未发现冻结记录
          }

          //车商信息
          $dealer = new Dealer($dealer_id);
          $dealer_info = $dealer->dealer_base_info();
          $db_freeze_amount = $dealer_info['freeze_amount'];
          $new_freeze_price = ($db_freeze_amount-$occur_money);
          if($new_freeze_price<0 || $new_freeze_price>$dealer_info['bail_amount']){
          AuctionException::make_throw('500054'); //保证金不能超过保证金总数，并且不能小于0
          }

          //更新冻结保证金
          $up_info = array();
          $up_info['freeze_amount'] = $new_freeze_price;
          $eff = M('car_dealer')->where("dealer_id='{$dealer_id}' and freeze_amount='{$db_freeze_amount}'")->save($up_info);
          if(!(intval($eff)>0)){
          AuctionException::make_throw('500052');
          }

          //生成冻结描述
          $row = M()->query("SELECT CONCAT('解冻出价保证金，  拍品【',pad.`city_name`,ad.`city_name`,'】 ',mb.`name` ,' ',s.`name` ,m.`name`,' 。') msg
          FROM  au_order o
          LEFT JOIN au_cars car ON car.car_id = o.`car_id`
          LEFT JOIN au_addr_area ad ON car.reg_city=ad.city_code
          LEFT JOIN au_addr_area pad ON ad.pid=pad.city_code
          LEFT JOIN au_car_model m ON car.`model_id` = m.`model_id`
          LEFT JOIN `au_car_series` s ON m.`series_id` = s.`series_id`
          LEFT JOIN au_car_brand b ON s.`brand_id` = b.`brand_id`
          LEFT JOIN au_car_mbrand mb ON b.`mbrand_id` = mb.`mbrand_id`
          WHERE  o.`order_id` = {$order_id} ;");
          if(count($row)>0){
          $msg = $row[0]['msg'];
          }

          //保证金使用记录
          $bail_log_info = array(
          'dealer_id'=>$dealer_id //int(10)车商id
          ,'order_id'=>$order_id //int(10)拍单号
          ,'use_time'=>$use_time //datetime保证金使用时间
          ,'use_type'=>3 //smallint(3)保证金应用类型 冻结出价保证金
          ,'use_detail'=>$msg //text应用明细
          ,'occur_money'=>$occur_money //double(10,2)发生金额
          ,'remain_amount'=>$dealer_info['bail_amount']  //余额
          ,'createtime'=>$now //datetime创建时间
          ,'free_bl_id'=>$info['bl_id']
          );
          $log_id = $bail_log->add($bail_log_info);
          return true;
         */
    }

    /**
     * 提取保证金
     * @param int $occur_money 发生金额
     * @param string $msg 描述
     * @return true/false
     */
    public function extract($occur_money, $msg = '提取保证金') {
        return $this->deduct($occur_money, 1, '', $msg);
    }

    /**
     * 争议支出保证金
     * @param int $occur_money 发生金额
     * @param int $order_id 相关拍单号
     * @param string $msg 描述
     * @return true/false
     */
    public function dispute_pay($occur_money, $order_id, $msg = '争议支出保证金') {
        return $this->deduct($occur_money, 2, $order_id, $msg);
    }

    /**
     * 赔付保证金
     * @param int $occur_money 发生金额
     * @param int $order_id 相关拍单号
     * @param string $msg 描述
     * @return true/false
     */
    public function compensate($occur_money, $order_id, $msg = '违约赔付保证金') {
        return $this->deduct($occur_money, 3, $order_id, $msg);
    }

    /**
     * 扣除车商保证金
     * @param int $occur_money 发生金额
     * @param int $de_type 1提取 2争议支出 3违约赔付
     * @param int $order_id 拍单号
     * @param string $msg 描述
     * @return true/false
     */
    private function deduct($occur_money, $de_type, $order_id, $msg = '') {
        $dealer_id = $this->dealer_id;

        if (!is_numeric($dealer_id) || $dealer_id <= 0) {
            AuctionException::make_throw('500001');
        }
        if (!is_numeric($occur_money) || $occur_money <= 0) {
            AuctionException::make_throw('500004');
        }

        $use_types = array(1 => 4, 2 => 5, 3 => 6);
        if (!array_key_exists($de_type, $use_types)) {
            AuctionException::make_throw('500056');
        }
        $dealer = M('car_dealer');

        $info = $dealer->field('bail_amount')->where("dealer_id='{$dealer_id}'")->find();
        $bail_amount = $info['bail_amount'];
        if ($occur_money > $bail_amount) {
            AuctionException::make_throw('500051'); //保证金不足
        }

        $now = date("Y-m-d H:i:s", time());
        //追加保证金记录
        $bail_log_info = array(
            'dealer_id' => $dealer_id //int(10)车商id
            , 'order_id' => $order_id //int(10)拍单号
            , 'use_type' => $use_types[$de_type] //smallint(3)保证金应用类型 扣除
            , 'use_detail' => $msg //text应用明细
            , 'occur_money' => $occur_money //double(10,2)发生金额
            , 'remain_amount' => ($bail_amount - $occur_money)  //余额
            , 'createtime' => $now //datetime创建时间
            , 'use_time' => $now //datetime保证金使用时间
        );
        $bail_log = M('dealer_bail_log');
        $log_id = $bail_log->add($bail_log_info);

        if (intval($log_id) > 0) {
            //更新保证金总数          
            $ok = $dealer->where("dealer_id='{$dealer_id}'")->setDec('bail_amount', $occur_money);
            if ($ok) {
                if ($use_types[$de_type] == 5 || $use_types[$de_type] == 6) {
                    //增加累计赔付总数
                    $dealer->where("dealer_id='{$dealer_id}'")->setInc('indemnity_amount', $occur_money);
                }
            }
            return $ok;
        }

        return false;
    }

    /**
     * 保证金消费记录
     */
    public  static function pay_money($dealer_id,$occur_money,$remain_amount,$collection_id,$use_detail='查询维修保养扣款'){
        $bail_log = M('dealer_bail_log');
        $time = date('Y-m-d H:i:s');
        $data= array(
            'dealer_id'=>$dealer_id,
            'use_time'=>$time,
            'use_type'=>8,
            'use_detail'=>$use_detail,
            'occur_money'=>$occur_money,
            'remain_amount'=>$remain_amount,
            'createtime'=>$time,
            'collection_id'=>$collection_id
        );
        return $bail_log->add($data);
    }

    /**
     * 推送收银台数据
     * @param $collection_no
     * @param $amount
     * @return mixed
     */
    public static function collection_log($collection_no,$amount,$type){
        $collection_log = M('collection');
        $time = date('Y-m-d H:i:s');
        $data = array(
            'collection_no'=>$collection_no,
            'status'=>1,
            'payment_type'=>$type,
            'payment_method'=>1,
            'amount'=>$amount,
            'emp_id'=>1,
            'emp_name'=>'系统管理员',
            'create_time'=>$time,
            'update_time'=>$time
        );
        return $collection_log->add($data);
    }

    /**获取最新日志log ID
     * @param $dealer_id
     * @param $occur_money
     * @param $user_type
     * @return mixed
     */
    public static function last_bail_log($dealer_id,$occur_money,$user_type){
        $bail_log = M('dealer_bail_log')->where(array('dealer_id'=>$dealer_id,'occur_money'=>$occur_money,'use_type'=>$user_type))->order('bl_id desc')->find();
        if($bail_log){
            return $bail_log['bl_id'];
        }
        return 0;
    }
}

?>